<?php

namespace frieza\Modules\Oauthadmin\Controllers;


use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Common\Lib\Parse\ObjIdParse;
use Doctrine\DBAL\Types\ObjectType;
use Doraemon\amqp\CommunityQueue;
use Doraemon\cache\AnswerCounter;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\BlankCounter;
use Doraemon\cache\GuideCounter;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\Photos as cPhotos;
use Doraemon\cache\Queue;
use Doraemon\model\AdmAnswer;
use Doraemon\model\AdmRecommPhoto;
use Doraemon\model\AdmUserType;
use Doraemon\model\Answer;
use Doraemon\model\Article;
use Doraemon\model\BestArticle;
use Doraemon\model\Blank;
use Doraemon\model\Comment;
use Doraemon\model\MemberBrand;
use Doraemon\model\MemberExtendInfo;
use Doraemon\model\MyArticleList;
use Doraemon\model\Photos;
use Doraemon\model\RecommendArticle;
use Doraemon\service\BindDesignerArticle as sBindDesignerArticle;
use Doraemon\service\MainTag;
use Doraemon\service\Member as sMember;
use Doraemon\model\Member as mMember;
use Doraemon\model\MemberUnregister;
use Doraemon\model\Phone;
use Doraemon\model\Qq;
use Doraemon\model\Sina;
use Doraemon\model\Weixin;
use Doraemon\model\Designer;
use Doraemon\service\RecommendQuestion;
use Doraemon\service\RecommendQuestion313;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Member;
use Doraemon\service\User as sUser;
use Biz\model\brand\Brand;
use Doraemon\cache\Article as cArticle;

//UnregisterController 账号注销申请的类
class UnregisterController extends Controller
{

    //index 账号注销申请入口
    public function index(Request $request, Content $content)
    {

        $page = $request->input("page", 1);
        $pageSize = $request->input("per_page", 20);
        $status = MemberUnregister::STATUS_NORMAL;

        $infos = MemberUnregister::getUnregisterList($status, $page, $pageSize);
        $count = MemberUnregister::countUnregister($status);

        $gridModel = new pGridDataModel($infos, $count, ["per_page" => $pageSize]);

        $listGrid = Admin::grid($gridModel, function(Grid $grid){
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();

            $grid->column("uid")->display(function() {
                return "<a href='/admin/user/Detail/$this->uid' target='_blank' >".$this->uid."</a>";
            })->width(100);

            $grid->column("nick", "昵称")->display(function(){
                if(empty($this->nick)){
                    $userInfo = mMember::getUser($this->uid);
                    return $userInfo["nick"];
                }else{
                    return $this->nick;
                }
            });

            $grid->column("type", "用户身份")->display(function(){
                $userInfo = sMember::getUserInfoByUid($this->uid);
                return self::FormateType($this->uid,$userInfo['type']);
            });

            $grid->column("picture", "头像")->display(function(){
                $userInfo = sMember::getUserInfoByUid($this->uid);
                $avatarPicUrl = User::getUserAvatarPicUrl($this->uid,$userInfo["avatar_version"]);

                return '<img src = "'.$avatarPicUrl[0].'" width = 45px height = 45px />';
            });

            $grid->column("blindMethod", "绑定方法")->display(function (){
                $temp = [];
                $sinaModel = Sina::getSinaUidByUid($this->uid);
                if ($sinaModel){
                    $temp["sina"] = "微博";
                }

                $weixinModel = Weixin::getOpenidByUid($this->uid);
                if ($weixinModel){
                    $temp["weixin"] = "微信";
                }

//                $phoneModel = Phone::getUserPhone($this->uid);
//                if ($phoneModel){
//                    $temp["phone"] = "手机";
//                }

                $phoneModel = Phone::getByUid($this->uid);
                if ($phoneModel['phone']) {
                    $temp["phone"] = "手机";
                }

                $qqModel = Qq::getOpenidByUid($this->uid);
                if ($qqModel){
                    $temp["qq"] = "QQ";
                }

                $data = implode("、", $temp);
                return $data;
            });

            $grid->column("uptime", "最后申请日期")->display(function (){
                return date("Y-m-d H:i:s", $this->uptime);
            });

            $grid->column("overtime", "剩余处理时间")->display(function(){
                $overtime = ceil(3 - ( time() - $this->uptime ) / 86400 );
                return $overtime;
            });

            $grid->actions(function (Actions $actions){
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
                $actions->prepend('<a class="fa reload-data fa-eye-slash received-package" data-uid="'.$actions->row->uid.'" data-opt = "忽略" href="javascript:;" >忽略</a>');
                $actions->prepend('<a class="fa reload-data fa fa-ban received-package" data-uid="'.$actions->row->uid.'" data-opt = "注销" href="javascript:;" >注销</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            });

            Admin::script($this->optionSubmit());

        });

        $tab = new Tab();
        $tab->add("账号注销申请", $listGrid->render());
        $content->row($tab);
        return $content
            ->header("注销账号")
            ->breadcrumb(['text' => '账号注销申请']);
    }

    //ignoreUser 确认忽略逻辑
    public function ignoreUser(Request $request)
    {

        $request = $request->all();
        $uid = $request['uid'];
        $status = MemberUnregister::STATUS_IGNORE;
        $operater = Admin::user()->id;

        $condition = [
            "status" => $status,
            "operater" => $operater,
            "unregisttime" => time()
        ];

        $ok = MemberUnregister::updateById($uid, $condition);
        if ($ok) {
            $data = [
                'code' => 1,
                'msg' =>"忽略成功"
            ];
        }else{
            $data = [
                'code' => 0,
                'msg' => '忽略失败'
            ];
        }
        $data['uid'] = $uid;

        return $data;
    }

    //cancellationUser 确认注销逻辑
    public function cancellationUser(Request $request){

        $request = $request->all();
        $uid = $request['uid'];

        $userInfo = mMember::getUser($uid);

        //hhz_unregister表注销
        $condition = [
            "nick" => $userInfo["nick"],
            "status" => MemberUnregister::STATUS_DELETE,
            "operater" => Admin::user()->id,
            "unregisttime" => time()
        ];
        $ok = MemberUnregister::updateById($uid, $condition);
        //$ok = 1;

        //hhz_member表注销
        $rel = mMember::updateUserInfo($uid, [
            "status" => mMember::STATUS_UNREGISTER,
            "nick" => "已注销" .time()
        ]);

        //hhz_designer表注销
        Designer::updateDesigner($uid, ["status" => Designer::STATUS_DELETE]);

        //hhz_member_extend_info表注销
        MemberExtendInfo::addFieldByUid($uid, ["status" => MemberExtendInfo::STATUS_DELETE]);

        //hhz_brand表注销
        MemberBrand::updateBrandByUid($uid, ["status" => MemberBrand::STATUS_DEL]);

        if ($rel && $ok){
            //hhz_admin_user_type表
            AdmUserType::addIdentityMark([$uid], "已注销");

            \Doraemon\cache\SolrUpdateCollector::insert($uid);
            \Doraemon\cache\EsUpdateCollector::insert($uid);

            // 删除QQ、微信、微博、电话
            Phone::delOne($uid);
            Weixin::delOne($uid);
            Qq::delOne($uid);
            Sina::delOne($uid);

            //图片删除
            $photos = Photos::getPhotosByUid($uid);
            AdmRecommPhoto::deleteByUid($uid);
            if($photos) {
                foreach ($photos as $photoInfo) {
                    $id = $photoInfo;
                    Photos::updatePhotoById($id, ["status" => Photos::STATUS_DELETE, 'show_status' => Photos::SHOW_STATUS_INVISIBLE]);
                    CommunityQueue::insertQueue('queue/Photo/delPhoto',['photo_id' => $id], CommunityQueue::QUEUE_COMMUNITY);
                    cPhotos::delete($id);

                }
                CommunityQueue::insertQueue(
                    '/queue/Photo/delUserNewPhotoCache',
                    ['uid' => $uid],
                    CommunityQueue::QUEUE_COMMUNITY);

            }

            //回答删除
            $answerIds = Answer::getAnsweridsByuid($uid);
            if ($answerIds && is_array($answerIds)){
                foreach ($answerIds as $id) {
                    $answerInfo = Answer::getAnswerById($id);
                    $result = Answer::updateAnswerById($id, ["status" => Answer::STATUS_DELETE]);
                    if ($request) {
                        AdmAnswer::deleteAnswerById($id);
                        RecommendQuestion::delHotBestAnswer($answerInfo['q_id'], $id);
                        RecommendQuestion313::delHotBestAnswer($answerInfo['q_id'], $id);

                        Queue::insertQueue('Question/delRplQuestionToFeed', [
                            'a_id' => $id
                        ]);
                        Queue::insertQueue('Question/interaction', [
                            'q_id' => $answerInfo['q_id'],
                            'act' => 'cancel_answer'
                        ]);
                    }
                }
            }

            //整屋删除
            $articleIds = Article::getNorAidsByUid($uid);
            if($articleIds && is_array($articleIds)) {
                foreach ($articleIds as $aid) {
                    $articleInfo = Article::getInfoByAid($aid);
                    Article::updateArticle($aid, [
                        'admin_score' => 1,
                        'status' => Article::STATUS_FORCE_OUT
                    ]);

                    //标签删除
                    if($articleInfo['main_tag']){
                        $mainTagArr = explode(",", $articleInfo['main_tag']);
                        foreach ($mainTagArr as $mainTag){
                            MainTag::handleEditMainTag(trim($mainTag), $aid);
                        }
                    }

                    $res = BestArticle::getOneArticle($aid);
                    if ($res){
                        BestArticle::updateArticle($aid, [
                            'status' => BestArticle::STATUS_DELETE
                        ]);
                    }

                    $res = MyArticleList::getInfoByObjId($aid);
                    if ($res){
                        MyArticleList::delByObjId($aid);
                    }

                    $res = RecommendArticle::getByAid($aid);
                    if($res){
                        RecommendArticle::delete(['aid' => $aid]);
                    }

                    Queue::insertQueue('Article/delArticle' , array('article_id' => $aid));
                    cArticle::delete($aid);
                    sBindDesignerArticle::addBindArticle($aid);
                    Queue::insertQueue('TotalArticle/delArticleById',array('article_id' => $aid));

                }
            }

            //文章删除
            $blankIds = Blank::getBlankidsByuid($uid);

            if($blankIds && is_array($blankIds)){
                foreach ($blankIds as $bid) {

                    $blankInfo = Blank::getBlankById($bid);
                    Blank::updateById($bid, ['status' => Blank::STATUS_FORCE_OUT]);
                    if ($blankInfo['main_tag']) {
                        $mainTagArr = explode(",", $blankInfo['main_tag']);
                        foreach ($mainTagArr as $mainTag) {
                            MainTag::handleEditMainTag(trim($mainTag), $bid);
                        }
                    }

                    $res = MyArticleList::getInfoByObjId($bid);
                    if ($res){
                        MyArticleList::delByObjId($bid);
                    }

                    if ($res){
                        Queue::insertQueue('Blank/deleteBlank', ['blank_id' => $bid]);
                        Queue::insertQueue('TotalArticle/delArticleById',['article_id' => $bid]);
                    }
                }
            }

            //评论删除
            $commentInfos = Comment::getCommentsByUid($uid);
            if ($commentInfos && is_array($commentInfos)) {
                foreach ($commentInfos as $commentInfo) {
                    $result = Comment::admDelComment($commentInfo['obj_id'], $commentInfo['id'], Admin::user()->id, $commentInfo['obj_type']);
                    if ($result) {
                        $objType =substr($commentInfo['obj_id'], 7, 2);
                        if($objType === '00'){
                            PhotoCounter::decreasePhotoCounter($commentInfo['obj_id'], PhotoCounter::ACT_COMMENT);
                        }else if($objType === '01'){
                            ArticleCounter::decreaseArticleCounter($commentInfo['obj_id'], ArticleCounter::ACT_COMMENT);
                        }else if($objType === '02'){
                            GuideCounter::decreaseGuideCounter($commentInfo['obj_id'], GuideCounter::ACT_COMMENT);
                        }else if($objType === '04'){
                            AnswerCounter::increaseAnswerCounter($commentInfo['obj_id'], AnswerCounter::ACT_COMMENT);
                        }else if($objType === '05'){
                            BlankCounter::decreaseBlankCounter($commentInfo['obj_id'], BlankCounter::ACT_COMMENT);
                        } else if ($commentInfo['obj_type'] == Comment::LEGO_COMMENT_TYPE) {
                            $cacheId = $commentInfo['obj_id'].':'.$commentInfo['obj_type'];
                            \Doraemon\cache\LegoCounter::decreaseLegoCounter($cacheId, \Doraemon\cache\LegoCounter::ACT_COMMENT);
                        }

                    }

                }

            }

            Queue::insertQueue('User/delUserinfoCache', ['uid' => $uid]);
            Queue::insertQueue('User/delTokenCache', ['uid' => $uid]);
            Queue::insertQueue('User/delSolrUserInfo', ['uid' => $uid]);

            $data = [
                'code' => 1,
                'msg' => "注销成功"
            ];
        }else{
            $data = [
                'code' => 0,
                'msg' => "注销失败"
            ];
        }

        return $data;
    }

    //所选操作提交
    public function optionSubmit()
    {
        return <<<SCRIPT
           
            $('.received-package').unbind('click').click(function() {
            var uid = $(this).data('uid');
            var opt = $(this).data('opt');
            swal({
                title: "是否确认"+opt+"?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    if(opt == "注销"){
                        $.post('cancellationUser', {'uid':uid}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.msg, '', 'success');
                             } else {
                                swal(data.msg, '', 'error');
                             }                                                                                                                                    
                        });
                    } else {
                        $.post('ignoreUser', {'uid':uid}, function (data) {
                             $.pjax.reload('#pjax-container');
                             if(data.code == 1) {
                                swal(data.msg, '', 'success');
                             } else {
                                swal(data.msg, '', 'error');
                             }                                                                                                                                    
                        });
                    }
                    
                }
            });
        });
SCRIPT;
    }

    public static function FormateType($uid,$type)
    {
        $all_type = Member::$typeDesc;
        foreach ($all_type as $key => $value){
            if ($type == Member::AUTH_USER_BRAND){
                $brand_type = sUser::getBrandInfo($uid)['type'];
                if ($brand_type == Brand::TYPE_BRAND){
                    $type = '认证品牌';
                }elseif ($brand_type == Brand::TYPE_SHOP){
                    $type = '认证店铺';
                }
            }elseif($type == $key) {
                $type = $value;
            }
        }

        return $type;
    }

}